export default {
	/**
	 * 猫酷登陆
	 */
	loginFunc(id, login_link, login_scope, success_redirect, error_redirect) {
		// 授权ID
		id = parseInt(id) || 0
		// 当前链接
		let nowLink = window.location.href
		if (!id) {
			console.log('账号配置错误')
			// 进行安全处理
			let safeLink = nowLink.replace(/[?|&]mc_id=[%+-_0-9a-zA-z]*/, '')
			if (nowLink !== safeLink) {
				// 清除历史记录，避免回退
				window.history.forward(1)
				window.location.href = safeLink
			}
			return null
		}
		let loginStatus = this.loginCheckFunc(id)
		console.log('登陆状态：', loginStatus)
		if (loginStatus) {
			return loginStatus;
		}
		let redirectLink = login_link || ''
		if (!redirectLink) {
			console.log('登陆配置错误')
			return null
		}
		// 跳转到授权页
		redirectLink += redirectLink.indexOf('?') == -1 ? '?' : '&'
		redirectLink += 'mc_id=' + id
		redirectLink += login_scope ? '&mc_scope=' + login_scope : ''
		if (success_redirect) { // 成功回调
			redirectLink += '&success=' + btoa(encodeURI(success_redirect))
		} else { // 回调到当前页
			redirectLink += '&success=' + btoa(encodeURI(nowLink))
		}
		if (error_redirect) {
			redirectLink += '&error=' + btoa(encodeURI(error_redirect))
		}
		console.log('登陆地址：', redirectLink)
		window.location.href = redirectLink
		return null
	},
	/**
	 * 登陆拦截
	 */
	loginCheckFunc(id) {
		// 取得登ID
		id = this.getQueryStringFunc('mc_id') || id
		console.log('登陆ID', id)
		if (!id) {
			return false
		}
		// 取得本地TOKEN
		let vuex_token = uni.getStorageSync('vuex_mc_token') || ''
		console.log('本地TOKEN', vuex_token)
		// 取得授权TOKEN
		let link_token = this.getQueryStringFunc('mc_token') || ''
		console.log('授权TOKEN', link_token)
		// 判断是否登陆
		if (!vuex_token && !link_token) {
			return false
		}
		// 更新TOKEN
		if (link_token && link_token != vuex_token) {
			uni.setStorageSync('vuex_mc_token', link_token);
			// 进行安全处理
			let nowLink = window.location.href
			let safeLink = nowLink.replace(/[?|&]mc_token=[%+-_0-9a-zA-z]*/, '')
			if (nowLink !== safeLink) {
				// 清除历史记录，避免回退
				window.history.forward(1)
				window.location.href = safeLink
			}
			return true
		}
		return true
	},
	/**
	 * 获取链接参数
	 * @param {Object} name
	 */
	getQueryStringFunc(name) {
		if ((new RegExp('(^|\\?|&)' + name + '=([^&]*)(\\s|&|$)', 'i')).test(window.location.href)) {
			return unescape(RegExp.$2.replace(/\+/g, ''))
		}
		return false
	}
}
